<template>
  <div class="data-boat">
    <h1 class="page-title">椒江区人才社区数据看板</h1>
    <!-- 概览数据卡片 -->
    <div class="data-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="overview-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon locations">
                <el-icon class="icon"><DataAnalysis /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-label">点位总数量</div>
                <div class="card-value">{{ overviewData.totalSpotCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon infrastructure">
                <el-icon class="icon"><OfficeBuilding /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-label">服务站点数量</div>
                <div class="card-value">
                  {{ overviewData.serviceCount }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 公共资源分类数据 -->
    <div class="data-section">
      <h2 class="section-title">公共资源数据</h2>
      <el-row :gutter="20">
        <el-col :span="8" v-for="(item, index) in publicData" :key="index">
          <el-card class="data-card" shadow="hover">
            <div class="card-header">
              <img class="category-icon" v-if="item.icon" :src="item.icon" alt="" />
              <span class="category-name">{{ item.name }}</span>
            </div>
            <div class="card-data">
              <div class="data-item">
                <span class="data-label">设施数量：</span>
                <span class="data-number">{{ item.count }}</span>
              </div>
              <el-progress :percentage="item.count" :show-text="false" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 服务站点分类数据 -->
    <div class="data-section">
      <h2 class="section-title">服务站点分类数据</h2>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <div slot="header" class="chart-header">
              <span>各类型站点数量</span>
            </div>
            <div class="chart-container" ref="serviceDataChart">
              <!-- 这里将使用 ECharts 图表 -->
              <div ref="chartDom" style="width: 450px; height: 300px"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <div slot="header" class="chart-header">
              <span>各站点占比</span>
            </div>
            <div class="table-container">
              <el-table
                :data="serviceData"
                style="width: 100%"
                :show-header="false"
              >
                <el-table-column prop="name" label="类型" width="180">
                  <template #default="scope">
                    <div class="station-type">
                      <span
                        class="dot"
                        :style="{ backgroundColor: getRandomColor() }"
                      ></span>
                      {{ scope.row.name }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="value" label="数量" width="80">
                  <template #default="scope">
                    <span>{{ scope.row.count }}个</span>
                  </template>
                </el-table-column>
                <el-table-column prop="percentage" label="百分比">
                  <template #default="scope">
                    <el-progress
                      :percentage="(scope.row.count / total) * 100 || 0"
                      :format="percentFormat"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onUnmounted } from 'vue'
import {
  DataAnalysis,
  Location,
  OfficeBuilding,
  Box,
} from '@element-plus/icons-vue'
import { dashboardAPI } from '@/api/index.js'
import { ElMessage } from 'element-plus'
// 概览数据
const overviewData = ref({
  totalSpotCount: 1,
  publicCount: null,
  serviceCount: 1,
  shareCount: 1,
})

// 公共资源分类
const publicData = ref()

// 服务站点数据
const serviceData = ref()

// 加载状态
const loading = ref(true)

// 格式化百分比显示
const percentFormat = (percentage) => {
  return percentage.toFixed(2) + '%'
}
const chartDom = ref(null)
let myChart = null
// 初始化图表
const initChart = () => {
  myChart = echarts.init(chartDom.value)

  // 处理数据，生成饼图所需的格式
  const chartData =
    serviceData.value?.map((item) => ({
      name: item.name,
      value: item.count,
    })) || []

  // 配置项对象
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'vertical',
      left: 'right',
      top: 'middle',
      textStyle: {
        fontSize: 12,
        color: '#606266',
      },
    },
    series: [
      {
        name: '服务站点',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['30%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: chartData,
        itemStyle: {
          borderRadius: 4,
          borderColor: '#fff',
          borderWidth: 2,
        },
      },
    ]
  }

  //使用配置
  myChart.setOption(option)
}

onUnmounted(() => {
  if (myChart) {
    myChart.dispose() // 销毁实例
  }
})

// 生成随机颜色函数
const getRandomColor = () => {
  // 方法1: 使用预定义的颜色数组
  const colors = [
    '#409eff',
    '#67c23a',
    '#e6a23c',
    '#f56c6c',
    '#909399',
    '#c71585',
    '#00ced1',
    '#ffa500',
    '#32cd32',
    '#ff69b4',
    '#87ceeb',
    '#dda0dd',
  ]
  return colors[Math.floor(Math.random() * colors.length)]
}

// 获取概览数据
const fetchOverviewData = async () => {
  try {
    const response = await dashboardAPI.getOverview()

    overviewData.value = response.data
  } catch (error) {
    console.error('获取概览数据失败:', error)
    ElMessage.error('获取概览数据失败')
  }
}

// 获取公共资源分类数据
const fetchpublicData = async () => {
  try {
    const response = await dashboardAPI.getPublicResourcesData()
    if (response.code === 200) {
      publicData.value = response.data
    }
  } catch (error) {
    console.error('获取公共资源数据失败:', error)
    ElMessage.error('获取公共资源数据失败')
  }
}
const total = ref(0)
// 获取服务站点统计数据
const fetchserviceDataData = async () => {
  try {
    const response = await dashboardAPI.getServiceData()
    if (response.code === 200) {
      serviceData.value = response.data
      total.value = serviceData.value.reduce((sum, item) => sum + item.count, 0)
      initChart()
    }
  } catch (error) {
    console.error('获取服务站点数据失败:', error)
    ElMessage.error('获取服务站点数据失败')
  }
}

// 初始化所有数据
const initData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchOverviewData(),
      fetchpublicData(),
      fetchserviceDataData(),
    ])
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.data-boat {
  padding: 20px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  height: 100%;
  overflow-y: auto;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.data-overview {
  margin-bottom: 30px;
}

.overview-card {
  height: 120px;
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.card-icon .icon {
  font-size: 28px;
  color: white;
}

.card-info {
  display: flex;
  flex-direction: column;
}

.card-label {
  font-size: 16px;
  color: #606266;
  margin-bottom: 5px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.infrastructure {
  background-color: #67c23a;
}

.locations {
  background-color: #e6a23c;
}

.shared-spaces {
  background-color: #f56c6c;
}

/* 分区标题 */
.data-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  color: #303133;
  margin-bottom: 20px;
  font-weight: 600;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

/* 数据卡片 */
.data-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.category-icon {
  width: 48px;
  height: 48px;
  margin-right: 10px;
}

.category-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.card-data {
  margin-top: 10px;
}

.data-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.data-label {
  color: #606266;
}

.data-number {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

/* 图表卡片 */
.chart-card {
  height: 350px;
  margin-bottom: 20px;
}

.chart-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
}

.chart-container {
  height: 280px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 表格样式 */
.table-container {
  height: 280px;
  overflow-y: auto;
}

.station-type {
  display: flex;
  align-items: center;
}

.dot {
  flex-shrink: 0;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 8px;
}

/* 空间数据表格 */
.space-chart {
  padding: 20px 0;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .el-col-6 {
    width: 50%;
  }

  .el-col-8 {
    width: 50%;
  }
}

@media (max-width: 768px) {
  .el-col-6,
  .el-col-8,
  .el-col-12 {
    width: 100%;
  }
}
</style>
